#!/usr/local/bin/perl -w

#
#     Zhejiang tianke
#     Author: Shangao
#     version 0.1
#     date: 2012-12-04
#     Lincese: GPL
#
#     Summary:


use strict;
use warnings;

if(@ARGV<2){
   print "usage:\t<fastqc_dir><output File>\n";
   exit;
}

my $fastqc_dir = shift;
my $out_file = shift;
my $str="$fastqc_dir/fastqc_data.txt";
open(IN, $str) || die "can't open the $str\n";
my $flag=0;my @array=(); my $total_Reads; my $length_Reads;
my $nflag=0; my $N_base; my $count;
while(<IN>){
   chomp;
   if($_=~m/Total Sequence/){
     #print $_."\n";
     my @a=split(/\t/, $_);
     $total_Reads=$a[1];
   }

   if($_=~m/Sequence length/)
   {
     #print $_."\n";
     my @a=split(/\t/, $_);
     $length_Reads=$a[1];

   }

  if($_=~m/\>\>END_MODULE/){
   $flag = 0; $nflag = 0;
   }

   if($flag==1){
   my @a = split(/\t/,$_);
   $array[$a[0]] = $a[1];
   }

   if($_=~m/\#Quality/){
   $flag = 1;
   #print $_."\n";
   }
   
   if($nflag==1){
   my @a=split(/\t/, $_);
   if($a[0]=~m/(\d+)-(\d+)/) {
   #print $2."\t".$1."\t".$a[1]."\n";
   $count=$2-$1+1;
   $N_base+=$a[1]*$count; 
   }elsif($a[0]=~m/\d+/){
   $N_base+=$a[1];
   }  

   }    
   
   if($_=~m/#Base\tN-Count/){
   $nflag = 1;
   #print $_."\n";
   }
}

close IN;

#for(my $i=2; $i<@array; $i++ ){
   #print $i."\t".$array[$i]."\n";
#}

my $r20=sumQReads(20, \@array);
my $f20=freqQReads($r20,$total_Reads);

my $r10=sumQReads(10, \@array);
my $f10=freqQReads($r10,$total_Reads);

$N_base*=$total_Reads;

open(OUT, ">$out_file") || die "can't open the $out_file\n";
print OUT $str."\n";
print OUT "Total Reads:\t".$total_Reads."\n";
print OUT "Length Reads\t".$length_Reads."\n";
print OUT "20\t".$r20."\n";
printf(OUT "20\t%.3f\n",$f20);
print OUT "10\t".$r10."\n";
printf(OUT "10\t%.3f\n",$f10);
printf(OUT "N_base\t%d\n", $N_base);
close OUT;

sub sumQReads{
  my ($qual, $ay) = @_;
  my $sum;
  for(my $i=$qual; $i<@$ay; $i++ ){
    if($array[$i]){
    $sum+=$array[$i];
    }
  }
  return $sum;
}

sub freqQReads{
  my ($QR, $total)=@_;
  return $QR/$total*100;
}
